package run.vue.iblog.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import run.vue.iblog.common.Result;
import run.vue.iblog.common.ResultFactory;
import run.vue.iblog.entity.Book;
import run.vue.iblog.service.BookService;
import run.vue.iblog.util.StringUtil;

import java.io.File;
import java.io.IOException;

@RestController
public class BookController {

    @Autowired
    private BookService bookService;


    // 获取所有书籍
    @GetMapping("/books")
    public Result list() throws Exception {
        return ResultFactory.success("读取图书成功",bookService.listAll());
    }

    // 更新或增加书籍
    @PostMapping("/books")
    public Result addOrUpdate(@RequestBody Book book) throws Exception {
        // 添加
        if(book.getId() == 0){
            book.setCid(book.getCategory().getId());
            System.out.println("Insert into book hahah");
            bookService.add(book);
        }else{
            // 修改
            int id = book.getCategory().getId();
            book.setCid(id);
            bookService.update(book);
        }
        return ResultFactory.success("更新或修改成功");
    }

    // 删除书籍
    @PostMapping("/delete")
    public Result delete(@RequestBody Book book) throws Exception {
        bookService.deleteById(book.getId());
        return ResultFactory.success("删除成功");
    }

    // 根据分类查询对应书籍
    @GetMapping("/categories/{cid}/books")
    public Result listByCategory(@PathVariable("cid") int cid) throws Exception {
        if (0 != cid) {
            return ResultFactory.success(bookService.listByCategory(cid));
        } else {
            // 获取所有书籍
            return ResultFactory.success(bookService.listAll());
        }
    }

    // 查找图书
    @GetMapping("/search")
    public Result searchResult(@RequestParam("keywords") String keywords) {
        // 关键词为空时查询出所有书籍
        if ("".equals(keywords)) {
            return ResultFactory.success(bookService.listAll());
        } else {
            return ResultFactory.success(bookService.search(keywords));
        }

    }

    // 书籍封面图片上传 随机字符串
    // 对接收到的文件重命名，但保留原始的格式
    @PostMapping("/books/covers")
    public String coversUpload(MultipartFile file) {
        // 文件实际存储位置
        System.out.println("请求了文件");
        String folder = "/usr/local/src/vueblog/api/bookImgs";
        File imageFolder = new File(folder);
        File f = new File(imageFolder, StringUtil.getRandomString(6) + file.getOriginalFilename()
                .substring(file.getOriginalFilename().length() - 4));
        if (!f.getParentFile().exists()){
            f.getParentFile().mkdirs();
        }
        try {
            file.transferTo(f);
            // 图片位置
            String imgURL = "http://121.36.49.42:9090/file/books/" + f.getName();
            return imgURL;
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }
}
